"""
PDF文本提取模块 - 提供不依赖MinerU的PDF文本提取功能
"""

import sys
import subprocess
from pathlib import Path

def extract_text_from_pdf(pdf_path):
    """使用PyPDF2提取PDF文本内容"""
    try:
        # 尝试导入PyPDF2
        try:
            import PyPDF2
        except ImportError:
            print("⚠️ PyPDF2库未安装，尝试安装...")
            subprocess.run([sys.executable, "-m", "pip", "install", "PyPDF2"], check=True)
            import PyPDF2
            print("✅ PyPDF2库安装成功")
        
        # 打开PDF文件
        with open(pdf_path, 'rb') as file:
            reader = PyPDF2.PdfReader(file)
            
            # 获取页数
            num_pages = len(reader.pages)
            print(f"📄 PDF文件共有 {num_pages} 页")
            
            # 提取文本
            text = []
            for i in range(num_pages):
                page = reader.pages[i]
                page_text = page.extract_text()
                if page_text:
                    text.append(f"## 第 {i+1} 页\n\n{page_text}\n\n")
            
            return "\n".join(text)
    except Exception as e:
        print(f"⚠️ 提取PDF文本失败: {e}")
        return None

if __name__ == "__main__":
    # 测试代码
    if len(sys.argv) > 1:
        pdf_path = sys.argv[1]
        text = extract_text_from_pdf(pdf_path)
        if text:
            print(f"成功提取文本，长度: {len(text)} 字符")
            print("文本预览:")
            print(text[:500] + "..." if len(text) > 500 else text)
        else:
            print("提取文本失败")
    else:
        print("用法: python pdf_extract.py <pdf_file_path>")